<?php

namespace app\api\controller\auth;

use app\common\controller\Api;
use think\Request;
use think\Cache;
use app\admin\model\User;
use app\common\library\Auth;
use GatewayWorker\Lib\Gateway;
use fast\Http;
use fast\Rsa;
class Login extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //注册账号
    public function register()
    {
        $phone = $this->request->post('phone'); //账号
        $password = $this->request->post('password'); //密码
        $passwordTwo = $this->request->post('passwordTwo'); //密码
        if($password != $passwordTwo){
            $this->error('两次密码输入不正确');
        }
        $existingUser = User::where('mobile', $phone)->find();
        if($existingUser){
            $this->error('此账号已经注册');
        }
        $auth = new Auth();
        $random_number = rand(10000, 99999);
        $encryptPassword = $auth->getEncryptPassword($password,$random_number);
        $data = [
            'mobile' => $phone,
//            'status'=>'normal',
            'password'=>$encryptPassword,
            'salt'=>$random_number,
            'jointime'=>time()
        ];
        $user = User::insertGetId($data);
        if($user){
            $this->success('注册成功');
        }
    }
    //登录
    public function login()
    {
        $phone = $this->request->post('phone'); //账号
        $password = $this->request->post('password'); //密码
        $existingUser = User::where('mobile', $phone)->find();
        if(!$existingUser){
            $this->error('此账号还未注册');
        }
        $auth = new Auth();
        $encryptPassword = $auth->getEncryptPassword($password,$existingUser->salt);
        if($encryptPassword == $existingUser->password){
            $this->auth->direct($existingUser['id']);
            $token = $this->auth->getToken();
            User::where('id', $existingUser['id'])->update(['status' => 'normal']);
            $this->success('登录成功',$token);
        }else{
            $this->error('密码错误');
        }
    }
    public function loginOut()
    {
        // 获取当前用户
        $user = $this->auth->getUser();
        // 销毁用户的令牌
        $this->auth->logout();
        // 更新用户状态（可选）
        User::where('id', $user['id'])->update(['status' => 'offline']);
        return $this->success('登出成功');
    }
}